package com.haois.mp.database.module.wxserver.service;

import com.haois.mp.database.commom.enums.ApiResultEnum;
import com.haois.mp.database.module.offaccounts.service.UserFollowService;
import com.haois.mp.database.module.wxserver.util.MapUtil;
import com.haois.mp.database.module.wxserver.util.TempMsgUtil;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.template.WxMpTemplate;
import me.chanjar.weixin.mp.bean.template.WxMpTemplateMessage;
import com.haois.mp.database.commom.enums.MpTypeEnum;

import com.haois.mp.database.module.common.daomain.BindState;
import com.haois.mp.database.module.common.daomain.TempMessage;
import com.haois.mp.database.module.common.daomain.WxUser;
import com.haois.mp.database.util.jx.GsonUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

import static com.haois.mp.database.module.wxserver.util.TempMsgUtil.temp_Default;
import static com.haois.mp.database.module.wxserver.util.TempMsgUtil.temp_Default_Color;


/**
 * Created by RuiHaoZ on 2018/4/4 19:51
 */
@Service
public class TempMessageService {

    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private BaseMessageService messageService;
    @Autowired
    private UserFollowService userFollowService;

    private Logger logger = LoggerFactory.getLogger(TempMessageService.class);


    public String sendTempMsgToUser(TempMessage tempMessage, String[] titleKey) throws WxErrorException {
        return this.sendTempMsgToUser(tempMessage, titleKey, temp_Default_Color);
    }

    public String sendTempMsgToUsern(TempMessage tempMessage) throws WxErrorException {
        return this.sendTempMsgToUser(tempMessage, temp_Default, temp_Default_Color);
    }

    public String sendTempMsgToUser(TempMessage tempMessage, String[] titleKey, String[] tempColor) throws WxErrorException {
        WxMpTemplateMessage tm = TempMsgUtil.createTemp(tempMessage, titleKey, tempColor);
        String reply = "推送: ";
        String replyWx = "";
        try {
            replyWx = wxMpService.getTemplateMsgService().sendTemplateMsg(tm);
            reply += replyWx;
        } catch (WxErrorException e) {
            e.printStackTrace();
            replyWx = e.getError().getJson();
            reply += replyWx;
        }
        try {
            reply += " ID:" + messageService.save(tm, tempMessage, replyWx);
        } catch (Exception e) {
            logger.error("保存模板消息出错:{}", e.getMessage());
            logger.error("模板消息内容为:{}", GsonUtil.toJson(tempMessage));
        }

        return reply;
    }

    public Map sendTempMsgToUserS(TempMessage tempMessage, String[] memberNum) throws WxErrorException {
        Map<String, String> mapData = tempMessage.getMapData();
        Map param_success = new HashMap();
        Set param_noFollow = new HashSet();
        List<BindState> bindStates = userFollowService.getBindState(memberNum, MpTypeEnum.OFFACCOUNTS.getType());
        Map<String, Boolean> receives = new HashMap<>();
        for (BindState bindState : bindStates) {
            if (bindState.isBindState()) {
                mapData.put("receiver", bindState.getMemberNum());
                tempMessage.setToUser(bindState.getOpenId());
                String reply = this.sendTempMsgToUser(tempMessage, TempMsgUtil.temp_Mass);
                param_success.put(bindState.getMemberNum(), reply);
            } else {
                receives.put(bindState.getMemberNum(), false);
                param_noFollow.add(bindState.getMemberNum());
            }
        }
        Map result = new HashMap();
        result.put("已推送", param_success);
        result.put("未关注", param_noFollow);
        int sum = param_noFollow.size() + param_success.size();
        String msg = "已推送:" + param_success.size() + "/" + sum
                + ",未关注:" + param_noFollow.size() + "/" + sum;
        Map map = MapUtil.createMap(ApiResultEnum.API_00.getCode(), msg, result);
        return map;
    }


    public WxMpTemplate getTemplateByTitle(String title) throws WxErrorException {
        List<WxMpTemplate> wxMpTemplates = this.getTempMsg();
        return TempMsgUtil.getTemplateByTitle(wxMpTemplates, title);
    }


    public Map sendTo(TempMessage tempMessage) throws WxErrorException {
        List<WxUser> wxUsers = new ArrayList<>();
        if (StringUtils.isNotBlank(tempMessage.getToUser())) {
            WxUser wxUser = userFollowService.getByOpenId(tempMessage.getToUser(), MpTypeEnum.OFFACCOUNTS.getType());
            if (wxUser != null) {
                wxUsers.add(wxUser);
            }
        } else {
            wxUsers = userFollowService.getBySubState(MpTypeEnum.OFFACCOUNTS.getType());
        }
        Map result = new HashMap();
        Map<String, String> mapData = tempMessage.getMapData();
        for (WxUser wxUser : wxUsers) {
            if (wxUser.getSubscribe()) {
                tempMessage.setToUser(wxUser.getOpenId());
                mapData.put("receiver", wxUser.getUserId());
                mapData.put("sender", "System");
                String reply = this.sendTempMsgToUser(tempMessage, TempMsgUtil.temp_Sys, TempMsgUtil.temp_Sys_Color);
                result.put(wxUser.getOpenId(), reply);
            } else {
                result.put(wxUser.getOpenId(), "未关注");
            }
        }
        return result;
    }

    public List<WxMpTemplate> getTempMsg() throws WxErrorException {
        List<WxMpTemplate> result = wxMpService.getTemplateMsgService().getAllPrivateTemplate();
        return result;
    }

    public void saveTempMsg(Map tempData, String timeId, String type) {
        messageService.save(tempData, timeId, type);
    }

    public Map<String, Object> getTempInfo(String id) {
        return messageService.getTempInfo(id);
    }
}
